<template>
	<div class="category-container">
		<el-form class="el_form" style="display: flex; justify-content: flex-start; padding: 10px 10px 10px 0">
			<el-button type="primary" @click="openAdd">添加分类</el-button>
		</el-form>

		<table-components :tableLoading="tableLoading" :tableData="tableData" @currentChange="currentChange">
			<el-table-column prop="categoryName" label="分类名称" align="center" />
			<el-table-column prop="weight" label="分类排序" align="center" />
			<el-table-column prop="createBy" label="创建人" align="center" />
			<el-table-column prop="createTime" label="创建时间" align="center" />
			<el-table-column label="操作" align="center">
				<template v-slot="scope">
					<el-button type="text" @click="openEdit(scope.row)">编辑</el-button>
					<el-button type="text" @click="del(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</table-components>

		<add :isAdd="isAdd" :dialogVisible="addVisible" :row="clickItem" @handleClose="addClose"></add>
	</div>
</template>

<script setup lang="ts" name="role">
import { onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { NextLoading } from '/@/utils/loading';
import TableComponents from '/@/components/tableComponents/index.vue';
import { getCategory, delCategory } from '/@/api/api';
import add from './dialog/add.vue';

const isAdd = ref(false);
const tableData = reactive({
	data: [],
	total: 0,
	page: 1,
	size: 20,
});
const tableLoading = ref(true);
const queryFrom = ref({});
const addVisible = ref(false);
const clickItem = ref({});

// 页面加载时
onMounted(() => {
	NextLoading.done();
	getData();
});

async function getData() {
	tableLoading.value = true;
	let par = {
		page: tableData.page,
		size: tableData.size,
		parentId: 0,
		...queryFrom.value,
	};

	let { code, data } = await getCategory(par);
	if (code == 200) {
		tableData.data = data.list;
		tableData.total = data.total;
		tableLoading.value = false;
	}
}

function openAdd(item) {
	isAdd.value = true;
	clickItem.value = item;
	addVisible.value = true;
}

function addClose() {
	isAdd.value = true;
	addVisible.value = false;
	getData();
}

function openEdit(item: any) {
	isAdd.value = false;
	clickItem.value = item;
	addVisible.value = true;
}

async function del(item: any) {
	ElMessageBox.confirm('是否确认删除分类?', 'Warning', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			handleDel(item);
		})
		.catch(() => {});
}

async function handleDel(item: any) {
	tableLoading.value = true;
	let par = {
		id: item.id,
	};

	let { code } = await delCategory(par);
	tableLoading.value = false;
	if (code == 200) {
		ElMessage.success('操作成功');
		getData();
	}
}
</script>

<style scoped lang="scss">
@import url('/@/theme/page/page.scss');
.category-container {
	padding: 0 20px 20px 20px;
}
</style>
